﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Web;
//using mp.message.req;
using mp.message.resp;

namespace mp.message.util
{
    /// <summary>
    ///MessageUtil 的摘要说明
    /// </summary>
    public class MessageUtil
    {

        // 返回消息类型：文本 
        public const String RESP_MESSAGE_TYPE_TEXT = "text";
        // 返回消息类型：音乐 
        public const String RESP_MESSAGE_TYPE_MUSIC = "music";
        // 返回消息类型：图文 
        public const String RESP_MESSAGE_TYPE_NEWS = "news";

        // 请求消息类型：文本 
        public const String REQ_MESSAGE_TYPE_TEXT = "text";
        // 请求消息类型：图片 
        public const String REQ_MESSAGE_TYPE_IMAGE = "image";
        // 请求消息类型：链接 
        public const String REQ_MESSAGE_TYPE_LINK = "link";
        // 请求消息类型：地理位置  
        public const String REQ_MESSAGE_TYPE_LOCATION = "location";
        // 请求消息类型：音频 
        public const String REQ_MESSAGE_TYPE_VOICE = "voice";
        //请求消息类型：视频
        public const String REQ_MESSAGE_TYPE_VIDEO = "video";
        // 请求消息类型：推送 
        public const String REQ_MESSAGE_TYPE_EVENT = "event";


        // 事件类型：subscribe(订阅) 
        public const String EVENT_TYPE_SUBSCRIBE = "subscribe";
        // 事件类型：unsubscribe(取消订阅) 
        public const String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
        // 事件类型：CLICK(自定义菜单点击事件) 
        public const String EVENT_TYPE_CLICK = "CLICK";

        /// <summary>
        /// 解析微信发来的请求（XML） 
        /// </summary>
        /// <param name="request">请求微信发来的XML格式数据</param>
        /// <returns>字典类型，将XML解析成键值对</returns>
        public static Dictionary<String, String> ParseXml(System.Web.HttpRequest request)
        {
            // 将解析结果存储在HashMap中  
            Dictionary<String, String> map = new Dictionary<String, String>();
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                // 从request中取得输入流  
                System.IO.Stream inputStream = request.InputStream;
                xmlDoc.Load(inputStream); //将流格式化为xml文档对象。
                XmlElement rootElement = xmlDoc.DocumentElement;// 得到xml根元素  
                XmlNodeList nodeList = rootElement.ChildNodes;//得到根元素下所有子节点集合

                foreach (XmlNode node in nodeList)
                {
                    map.Add(node.Name, node.InnerText);
                }
                inputStream.Close();
            }
            catch (Exception ex)
            {
                CommonFun.PrintExceptionLog(ex);
            }
            return map;
        }

        /// <summary>
        /// 文本消息对象转换成xml 
        /// </summary>
        /// <param name="textMessage">文本消息对象</param>
        /// <returns></returns>
        public static String TextMessageToXml(mp.message.resp.TextMessage textMessage)
        {
            string resXmlStr = "<xml>" +
                                   "<ToUserName><![CDATA[" + textMessage.ToUserName + "]]></ToUserName>" +
                                   "<FromUserName><![CDATA[" + textMessage.FromUserName + "]]></FromUserName>" +
                                   "<CreateTime>" + textMessage.CreateTime + "</CreateTime>" +
                                   "<MsgType><![CDATA[text]]></MsgType>" +
                                   "<Content><![CDATA[" + textMessage.Content + "]]></Content>" +
                               "</xml>";
            return resXmlStr;
        }

        /// <summary>
        /// 音乐消息对象转换成xml 
        /// </summary>
        /// <param name="musicMessage">音乐消息对象 </param>
        /// <returns></returns>
        public static String MusicMessageToXml(MusicMessage musicMessage)
        {
            string resXmlStr = "<xml>" +
                                   "<ToUserName><![CDATA[" + musicMessage.ToUserName + "]]></ToUserName>" +
                                   "<FromUserName><![CDATA[" + musicMessage.FromUserName + "]]></FromUserName>" +
                                   "<CreateTime>" + musicMessage.CreateTime + "</CreateTime>" +
                                   "<MsgType><![CDATA[music]]></MsgType>" +
                                   "<Music>" +
                                       "<Title><![CDATA[" + musicMessage.Music0.Title + "]]></Title>" +
                                       "<Description><![CDATA[" + musicMessage.Music0.Description + "]]></Description>" +
                                       "<MusicUrl><![CDATA[" + musicMessage.Music0.MusicUrl + "]]></MusicUrl>" +
                                       "<HQMusicUrl><![CDATA[" + musicMessage.Music0.HQMusicUrl + "]]></HQMusicUrl>" +
                                   "</Music>" +
                               "</xml>";
            return resXmlStr;
        }

        /// <summary>
        /// 图文消息对象转换成xml 
        /// </summary>
        /// <param name="newsMessage">图文消息对象</param>
        /// <returns></returns>
        public static String NewsMessageToXml(NewsMessage newsMessage)
        {
            string artile = "<xml><ToUserName><![CDATA[" + newsMessage.ToUserName + "]]></ToUserName><FromUserName><![CDATA[" + newsMessage.FromUserName + "]]></FromUserName><CreateTime>" + newsMessage.CreateTime + "</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>" + newsMessage.ArticleCount + "</ArticleCount><Articles>";
            string items = "";
            foreach (Article item in newsMessage.Articles)
            {
                items += "<item><Title><![CDATA[" + item.Title + "]]></Title> <Description><![CDATA[" + item.Description + "]]></Description><PicUrl><![CDATA[" + item.PicUrl + "]]></PicUrl><Url><![CDATA[" + item.Url + "]]></Url></item>";
            }
            return artile + items + "</Articles></xml>";
        }
        /// <summary>
        /// 将数据库中的news信息字段转化为artilce中的Items类型
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static List<Article> GetArticleItems(List<Dictionary<string,string>> items)
        {
            List<Article> artList = new List<Article>();
            foreach (Dictionary<string, string> dict in items)
            {
                Article item = new Article();
                item.Title = dict["Title"];
                item.Description = dict["Description"];
                item.PicUrl = dict["PicUrl"];
                item.Url = dict["Url"];
                artList.Add(item);
            }
            return artList;
        }

        /// <summary>
        /// 组合一个XML格式的NewsMessage
        /// </summary>
        /// <param name="toUserName"></param>
        /// <param name="fromUserName"></param>
        /// <param name="dict">含有有Article形式的Itmes项</param>
        /// <returns></returns>
        public static string RespXmlNewsMessage(string toUserName,string fromUserName,List<Dictionary<string, string>> dict)
        {
            NewsMessage newsMsg = new NewsMessage();
            newsMsg.ToUserName = fromUserName;
            newsMsg.FromUserName = toUserName;
            newsMsg.CreateTime = DateTime.Now.Ticks;
            newsMsg.MsgType = "news";

            newsMsg.ArticleCount = dict.Count;
            newsMsg.Articles = GetArticleItems(dict);
            string respXmlMessage =NewsMessageToXml(newsMsg);
            return respXmlMessage;
        }

        public static string RespXmlTextMessage(string toUserName, string fromUserName, string content)
        {
            TextMessage textMsg = new TextMessage();
            textMsg.ToUserName = fromUserName;
            textMsg.FromUserName = toUserName;
            textMsg.CreateTime = DateTime.Now.Ticks;
            textMsg.MsgType = "text";

            textMsg.Content = content;
            string respXmlMessage = TextMessageToXml(textMsg);
            return respXmlMessage;
        }

        public static string RespXmlMusicMessage(string toUserName, string fromUserName,Dictionary<string,string> dict)
        {
            Music music = new Music();
            MusicMessage musicMsg = new MusicMessage();
            musicMsg.ToUserName = fromUserName;
            musicMsg.FromUserName = toUserName;
            musicMsg.CreateTime = DateTime.Now.Ticks;
            musicMsg.MsgType = "music";

            music.Title = dict["Title"];
            music.Description = dict["Description"];
            music.MusicUrl = dict["MusicUrl"];
            music.HQMusicUrl = dict["HQMusicUrl"];
            musicMsg.Music0 = music;

            string respXmlMessage = MusicMessageToXml(musicMsg);
            return respXmlMessage;
        }
    }
}